import { config } from "../config/config";
import { Http } from "../utils/http";
import { promisic } from "../utils/util";

class Token {
    // 1.携带Token
    // server 请求Token

    // 登录 token -> storage

    // token 1. token不存在 2.token 过期时间

    async verify() {
        const token = wx.getStorageSync('token');
        if (!token) {
            await this.getTokenFromServer()
        } else {
            console.log(222);
            await this._verifyFromServer(token)
        }
    }

    async getTokenFromServer() {
        const { code } = await wx.login();
        const res = await promisic(wx.request)({
            url: `${config.localApiBaseUrl}token`,
            method: 'POST',
            data: {
                account: code,
                login_type: 0
            }
        });
        wx.setStorageSync('token', res.data.token);
        return res.data.token
    }

    async _verifyFromServer(token) {
        const res = await promisic(wx.request)({
            url: `${config.localApiBaseUrl}token/verify`,
            method: 'POST',
            data: {
                token: token
            }
        });
        const valid = res.data.is_valid
        if (!valid) {
            return this.getTokenFromServer()
        }
    }

}
export {
    Token
}